// Copyright (c) 2007, Brian Duff
// See LICENSE for license details.

package org.dubh.orablogs.ag;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Logger;

public final class Main
{
  private static final long SLEEP_TIME = 300000;
  private static final int NUM_THREADS = 25;
  private static final Logger LOG = Logger.getLogger( Main.class.getName() );
  
  public static void main(String [] args) throws InterruptedException
  {
    final OrablogsService service = new OrablogsService();

    ExecutorService exec = Executors.newFixedThreadPool( NUM_THREADS );

    while( true )
    {
      LOG.info( "Aggregator woke up..." );
      List<FetchFeed> tasks = new ArrayList<FetchFeed>();
      for ( Blog b : service.queryBloggersFindAll() )
      {
        FetchFeed task = new FetchFeed( b );
        tasks.add( task );
        exec.submit( task );
      }
      
      while ( !areAllTasksComplete( tasks ) )
      {
        Thread.sleep( SLEEP_TIME );        
        if ( !areAllTasksComplete( tasks ) )
        {
          LOG.info( "Tasks are not complete yet. Sleeping some more." );
        }
      }
    }    
  }
  
  private static boolean areAllTasksComplete( Collection<FetchFeed> tasks )
  {
    for ( FetchFeed task : tasks )
    {
      if ( !task.isComplete() ) return false;
    }
    return true;
  }
}
